package tau.dimes.visualization.applet;

import java.util.ArrayList;

import processing.core.PApplet;

/**
 * Calculates and draws the coordinates grid.
 */
class CoordinatesBackground
{
	private final DimesVApplet applet;
	private ArrayList<AngleCoordinatePair> vLines;
	private ArrayList<AngleCoordinatePair> hLines;

	/**
	 * Constructs a new CoordinatesBackground
	 * @param applet A reference to the containing applet.
	 */
	CoordinatesBackground(DimesVApplet applet)
	{
		this.applet = applet;
	}

	/**
	 * Calculates the coordinates of grid lines.
	 */
	public void calculate()
	{
		vLines = new ArrayList<AngleCoordinatePair>();
		hLines = new ArrayList<AngleCoordinatePair>();

		int leftAngleRound = PApplet.ceil(applet.leftAngle);
		int rightAngleRound = PApplet.floor(applet.rightAngle);
		int bottomAngleRound = PApplet.ceil(applet.bottomAngle);
		int topAngleRound = PApplet.floor(applet.topAngle);

		int hSkip = PApplet.max(1, (rightAngleRound - leftAngleRound) / 10);
		int vSkip = PApplet.max(1, (topAngleRound - bottomAngleRound) / 10);

		for (int hAngle = leftAngleRound; hAngle <= rightAngleRound; hAngle += hSkip)
			vLines.add(new AngleCoordinatePair(hAngle, applet.mapHAngle(hAngle)));

		for (int vAngle = bottomAngleRound; vAngle <= topAngleRound; vAngle += vSkip)
			hLines.add(new AngleCoordinatePair(vAngle, applet.mapVAngle(vAngle)));
	}

	/**
	 * Draws the grid lines.
	 */
	public void draw()
	{
		applet.strokeWeight(1);
		applet.textAlign(PApplet.LEFT);
		applet.textFont(applet.smallFont);
		applet.stroke(255, 127);
		applet.fill(255, 127);
		
		// draw vertical coordinate lines
		for (int i = 0; i < vLines.size(); i++)
		{
			AngleCoordinatePair p = vLines.get(i);
			applet.line(p.getCoordinate(), 0, p.getCoordinate(), applet.height);
			applet.text(p.getAngle().toString() + (char) 176, p.getCoordinate() + 2, 10);
		}

		// draw horizontal coordinate lines
		for (int i = 0; i < hLines.size(); i++)
		{
			AngleCoordinatePair p = hLines.get(i);
			applet.line(0, p.getCoordinate(), applet.width, p.getCoordinate());
			applet.text(p.getAngle().toString() + (char) 176, 2, p.getCoordinate() - 2);
		}
	}
}